/*
 * Copyright 2012 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.controller;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fujitsu.nanjing.tieba.base.BaseController;
import com.fujitsu.nanjing.tieba.common.ThirdVelocityEmailService;
import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.exception.Resource404Exception;
import com.fujitsu.nanjing.tieba.ibator.CoreUser;
import com.fujitsu.nanjing.tieba.service.BoardService;
import com.fujitsu.nanjing.tieba.service.SectionInfoService;
import com.fujitsu.nanjing.tieba.service.TopicService;
import com.fujitsu.nanjing.tieba.service.UserService;
import com.fujitsu.nanjing.tieba.view.velocity.tools.DomainTool;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

/**
 * IndexController.java
 * 
 * @author Qixiaobo-win8
 */
@Controller
public class IndexController extends BaseController {
	@Resource
	private Producer captchaProducer;
	@Resource
	private UserService userService;
	@Resource
	private ThirdVelocityEmailService thirdVelocityEmailService;
	@Resource
	private SectionInfoService sectionInfoService;
	@Resource
	private TopicService topicService;
	@Resource
	private BoardService boardService;
	private HashMap<String, Object> map = null;

	@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
	public String show(Model model) {
		return forward("/home/index");
	}
	/**
	 * 产生验证码的方法
	 * */
	@RequestMapping(value = "/captcha-image", method = RequestMethod.GET)
	public void createCaptcha(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");
		// return a jpeg
		response.setContentType("image/jpeg");
		// create the text for the image
		String capText = captchaProducer.createText();
		// store the text in the session
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,
				capText);
		// create the image with the text
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		// write the data out
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}
	@RequestMapping(value = "/error", method = RequestMethod.GET)
	public String showError(Model model) {
		return "error";
	}
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model, String error, HttpServletRequest request) {
		model.addAttribute("error", error);
		model.addAttribute("fromPath", request.getParameter("fromPath"));
		return forward("/myforum/login");
	}
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return forward("/myforum/register");
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout() {
		return forward("/myforum/logout");
	}

	@RequestMapping(value = "/perform/{userid}", method = RequestMethod.GET)
	public String peform(@PathVariable String userid) {
		return redirect("/myforum/perform/" + userid);
	}

	@RequestMapping(value = "/members/{memberId}", method = RequestMethod.GET)
	public String showMembers(@PathVariable String memberId, Model model) {
		return redirect("/forum/members/" + memberId);
	}

	@RequestMapping("/help")
	public String help() {
		return forward("/help/index");
	}
	@RequestMapping(value = {"/userlist"}, method = RequestMethod.GET)
	public String showMembers(Model model) throws Resource404Exception {
		return redirect("/userlist/pages/1");
	}

	@RequestMapping(value = {"/userlist/pages/{pageNum}"}, method = RequestMethod.GET)
	public String showMembersWithPageNum(Model model,
			@PathVariable String pageNum) throws Resource404Exception {
		List<CoreUser> users = null;
		try {
			users = userService.findUsersWithPageNum(Integer.parseInt(pageNum));
		} catch (NumberFormatException e) {
			throw new Resource404Exception("");
		}
		model.addAttribute("users", users);
		model.addAttribute("pageIndex", pageNum);
		model.addAttribute("pageCount", userService.findPageCount(null, false));
		return "userList/userList";

	}
	@RequestMapping(value = {"/userlist/{filter}"}, method = RequestMethod.GET)
	public String showMembersWithFilter(Model model, @PathVariable String filter)
			throws Resource404Exception {
		return redirect("/userlist/" + filter + "/pages/1");
	}

	@RequestMapping(value = {"/userlist/{filter}/pages/{pageNum}"}, method = RequestMethod.GET)
	public String showMembersWithPageNumAndFilter(Model model,
			@PathVariable String pageNum, @PathVariable String filter)
			throws Resource404Exception {
		List<CoreUser> users = null;
		filter = replce(filter);
		try {
			users = userService.findUsersWithPageNumAndFilter(
					Integer.parseInt(pageNum), filter);
		} catch (NumberFormatException e) {
			throw new Resource404Exception("");
		}
		model.addAttribute("users", users);
		model.addAttribute("pageIndex", pageNum);
		model.addAttribute("pageCount",
				userService.findPageCountWithFilter(filter));
		return "userList/userList";

	}
	@RequestMapping(value = "/findPwd", method = RequestMethod.GET)
	public String findPwd() {
		return "/myforum/findPwd";
	}
	@RequestMapping(value = "/findPwd", method = RequestMethod.POST)
	public String findPwd(Model model, String userId) {
		CoreUser user = userService.findById(userId);
		if (user == null) {
			model.addAttribute("message",
					new DomainTool().info("userNameError"));
			return "/myforum/perform";
		}
		Date expiredDate = userService.setPwdExpired(user);
		String checkUrl = getfindPwdUrl(expiredDate, user.getUserid());
		String email = user.getEmail();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("checkUrl", checkUrl);
		thirdVelocityEmailService.sendEmail(map, "请及时修改密码",
				"com/fujitsu/mailTemplates/changePwd.vm", new String[]{email},
				new String[]{});
		model.addAttribute("message", new DomainTool().info("findPwdSuccess")
				+ email);
		return "/myforum/perform";
	}
	@RequestMapping(value = "/findPwd/{userid}/{expiredDate}", method = RequestMethod.GET)
	public String findPwd(@PathVariable String userid,
			@PathVariable String expiredDate, Model model) {
		userid = decrypt(userid);
		expiredDate = decrypt(expiredDate);
		if (userService.checkValid(userid, expiredDate)) {
			model.addAttribute("user", userService.findById(userid));
			return "/myforum/changePwd";
		} else {
			model.addAttribute("message", new DomainTool().info("linkError"));
			return "/myforum/perform";
		}
	}
	public String getfindPwdUrl(Date date, String userName) {
		StringBuilder sb = new StringBuilder();
		sb.append("/findPwd/");
		sb.append(encrypt(userName));
		sb.append("/");
		sb.append(encrypt(date.toString()));
		return sb.toString();
	}
	@RequestMapping(value = "/findPwd/{userid}/{expiredDate}", method = RequestMethod.PUT)
	public String changePassword(Model model, String oldpwd, String pwd1,
			String pwd2, @PathVariable String userid,
			@PathVariable String expiredDate) {
		userid = decrypt(userid);
		CoreUser user = userService.findById(userid);
		if (user.getPwd().equals(encrypt(oldpwd))) {
			if (pwd1.equals(pwd2)) {
				user.setPwd(encrypt(pwd1));
				userService.update(user);
				model.addAttribute("message",
						new DomainTool().info("changePwdSuccess"));
				return "/myforum/perform";
			} else {
				model.addAttribute("message",
						new DomainTool().info("passwordNotSame"));
				return "/myforum/perform";
			}

		}
		model.addAttribute("message", new DomainTool().info("changePwdFail"));
		return forward("/findPwd");

	}
	@RequestMapping(value = "/advsearch", method = RequestMethod.GET)
	public String advSearch(Model model) {
		model.addAttribute("sectionInfos", sectionInfoService.findAll());
		return "/advSearch/advSearch";

	}
	@RequestMapping(value = "/advsearch/result", method = RequestMethod.GET)
	public String advSearch(Model model, String searchfield, String keys,
			String uid, String boardid) {
		initMap(searchfield, keys, uid, boardid);
		return redirect("/advsearch/result/pages/1");

	}
	@RequestMapping(value = "/advsearch/result/pages/{pageIndex}", method = RequestMethod.GET)
	public String advSearch(Model model, @PathVariable String pageIndex) {
		pageIndex = (pageIndex == null ? "0" : pageIndex);
		model.addAttribute("pageIndex", pageIndex);
		if (getMap() == null) {
			model.addAttribute("message", new DomainTool().info("searchError"));
			return "/myforum/perform";
		}
		map.put("offset", (Integer.parseInt(pageIndex) - 1)
				* CommonParamter.默认分页长度);
		if (map.get("searchfield").equals("title")) {
			model.addAttribute("topics", topicService.searchTopic(map));
			model.addAttribute("pageCount",
					topicService.findPageCountSearchTopics(map));
		} else {
			model.addAttribute("topics",
					topicService.searchTopicAndReplies(map));
			model.addAttribute("pageCount",
					topicService.findPageCountSearchTopicsAndReplies(map));
		}
		return "advSearch/result";

	}
	public Map<String, Object> initMap(String searchfield, String keys,
			String uid, String boardid) {
		if (uid == null)
			uid = "";
		if (keys == null)
			keys = "";
		setMap(new HashMap<String, Object>());
		getMap().put("keys", "%" + keys + "%");
		getMap().put("offset", 0);
		getMap().put("userid", "%" + uid + "%");
		getMap().put("searchfield", searchfield);
		if (boardid.equals("all")) {
			boardid = boardService.findAll();
		}
		getMap().put("boardid", boardid);
		return getMap();
	}
	public HashMap<String, Object> getMap() {
		return map;
	}
	public void setMap(HashMap<String, Object> map) {
		this.map = map;
	}
}
